<template>
	<view class="enter-game">
		<gameInfo :num="currentGameDTO.setting.playerCount" :date="currentGameDTO.date" :status="gameStatus"/>
		<seat seatTitle="玩家选座" seatTip="请点击座位,进行就座" :seatStatu="seatStatus" :seatList="gameSeatList"/>
		<!-- 游戏初始化阶段 -->
		<view v-if="gameStatus==='init' " >
			<uni-notice-bar text="游戏准备中，请根据主持人提示进行操作" />
			<view class="player-control">
				<view class="control-btn">
					<button class="mini-btn" type="warn" size="mini" @click="exit">离开游戏</button>
				</view>
				<view class="control-btn">
					<button class="mini-btn" type="primary" size="mini" @click="editGameRole">录入我的身份</button>
				</view>
			</view>
		</view>
		<!-- 游戏进行中阶段 -->
		<view v-else-if="gameStatus==='process'">
			<uni-notice-bar text="游戏已开始,请根据主持人提示进行游戏或投票" />
			<view  class="player-control">
				<view class="control-btn">
					<button class="managebtn" type="primary" :disabled="gameStageVoteStatus==='voting'" size="mini" @click="votePlayer">我要投票</button>
				</view>
				<view class="control-btn">
					<button class="mini-btn" type="primary" size="mini" @click="viewVoteRecord">查看投票记录</button>
				</view>
			</view>
		</view>
		<!-- 游戏结束阶段 -->
		<view v-else>
			<view class="player-control">
				<view class="control-btn">
					<button class="mini-btn" type="primary" size="mini" @click="gameReview">游戏复盘</button>
				</view>
				<view class="control-btn">
					<button class="mini-btn" type="primary" size="mini" @click="gameScore">查看得分</button>
				</view>
			</view>
		</view>
		<view>
			<!-- 离开提示窗 -->
			<uni-popup ref="exitGameDialog" type="dialog">
				<uni-popup-dialog type="warn" title="退出游戏" content="请确认是否退出本场游戏？" @confirm="subExitGame">
				</uni-popup-dialog>
			</uni-popup>
		</view>
		<view>
			<!-- 网络请求结果确认框 -->
		<uni-popup ref="message" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="2000">
			</uni-popup-message>
		</uni-popup>
		</view>
		<view>
			<!-- 角色身份输入框 -->
			<uni-popup ref="inputGameRoleDialog" type="dialog">
				<uni-popup-dialog ref="inputClose" mode="input" title="录入你的角色身份" value="" placeholder="请输入内容"
					@confirm="subEditGameRole">
					<view class="example-body">
						<uni-combox :candidates="gameRoleList" placeholder="点击在角色列表选择" v-model="currentGameRole">
						</uni-combox>
					</view>
				</uni-popup-dialog>
			</uni-popup>
		</view>
		<!-- 投票选择框 -->
		<uni-popup ref="voteDialog" type="dialog">
			<uni-popup-dialog class="dialog" :type="warn" title="请点击下方选择框投票" >
				<view class="vote-info">
					<view class="text">
						当前回合：{{gameStageCodeTrans}} 第{{gameStageCodeVoteTurns}}轮投票
					</view>
					<view class="text" v-if="voteRight">
						<uni-data-checkbox mode="tag"  v-model="voteCheckbox" :localdata="allowVotedPlayer"></uni-data-checkbox>
					</view>
					<view class="text" v-else>
						当前没有投票权限
					</view>
					<view class="player-control">
						<view class="control-btn">
							<button class="mini-btn" type="primary" :disabled="!voteRight" size="mini" @click="subVotePlayer">投票</button>
						</view>
						<view class="control-btn">
							<button class="mini-btn" type="warn" :disabled="!voteRight" size="mini" @click="abandonVote">弃票</button>
						</view>
					</view>
				</view>
				</uni-popup-dialog>
		</uni-popup>
		
	</view>	
</template>

<script>
	import gameInfo from '@/components/gameinfo.vue'
	import seat from '@/components/seat.vue'
	import { UID_KEY,GAME_ID,GAME_STATUS,GAME_STAGE } from '@/common/utils'
	import {addplayeraction,querygamedetail,querygamedetailbydm,submitgamerole,quitgame} from "@/common/api"
	import {mapState,mapMutations,mapGetters,mapActions} from "@/store/helper/dm"
	let timer
	export default {
		data() {
			return {
				gameRoleList: ["普通狼人", "平民", "预言家", "女巫", "猎人", "丘比特", "白痴", "守卫", "白狼王", "狼王", "狼美人"],
				currentGameRole: '',
				voteCheckbox:0,
				allowVotedPlayer: [],
				msgType: '',
				messageText: ''
				}
		},
		components: {gameInfo,seat},
		computed:{
			allowVoted(){
				//加载允许被投票玩家的列表
				let gamestageIndex = this.gameStageCode
				let voteTrunIndex = this.gameStageCodeVoteTurns
				if(Object.keys(this.stageInfoMap).length > 0 && gamestageIndex in this.stageInfoMap && Object.keys(this.stageInfoMap[gamestageIndex].voteInfoMap).length>0 ){
					console.log(this.gameStageCodeVoteTurns)
					let tmpVoteList = this.stageInfoMap[gamestageIndex].voteInfoMap[voteTrunIndex].limit.allowVotedPlayer
					for (let i = 0; i < tmpVoteList.length; i++) {
						this.allowVotedPlayer.push({text:tmpVoteList[i].toString(),value:i})
					}
				} else{
						//待优化 需要控制警长投票环节的权限，如有上警则不允许投票
						let tmpVoteList = Array.from(new Array(this.currentGameDTO.setting.playerCount + 1).keys()).slice(1)
						for (let i = 0; i < tmpVoteList.length; i++) {
							this.allowVotedPlayer.push({text:tmpVoteList[i].toString(),value:i})
						}
					}
			},			
			voteRight(){
				let gamestageIndex = this.gameStageCode
				if(Object.keys(this.stageInfoMap).length > 0 && this.gameStageCode in this.stageInfoMap && Object.keys(this.stageInfoMap[gamestageIndex].voteInfoMap).length>0 ){			
					//判断玩家是否存在允许投票玩家的列表内
					return this.allowVotedPlayer.includes(this.user.seatnumber)? "true" : "false"
				} else return "true"				
			},
			seatStatus(){
				return this.currentGamePlayerSeatNum ===0?"待选座":"已选座"
			},
			...mapState([
				"user",
				"gameStatus",
				"currentGameID",
				"currentGameDTO",
				"currentGamePlayerSeatNum",
				"gameStageCode",
				"gameStageVoteStatus",
				"stageInfoMap",
			]),
			...mapGetters([
				"gameStageCodeTrans",
				"gameRoleTrans",
				"gameSeatList",
				"gameStageCodeVoteTurns",
			])
		},
		onLoad(option){
			//接收页面参数
			this.setGameStageCode(option.queryGameCode)
			uni.setStorageSync('GAME_ID',option.queryGameCode)
			this.initGame()
			console.log(this.currentGameDTO.setting.playerCount)
		},
		onShow(){
			// #ifdef MP-WEIXIN
			//每隔7秒查询更新一次游戏信息
			let that = this
			this.timer = setInterval(function(){
				that.initGame();
				console.log(1);
				clearInterval(this.timer)
				},7000)
			if (this.gameStatus!= "init" ) {clearInterval(this.timer)}
			// #endif
		},
		onUnload(){
			//这里考虑功能兼容暂选择不缓存信息，后退再进入需重新加载
			clearInterval(this.timer)
			if(this.gameStatus!='init' || this.gameStatus!='process' ){
				this.clearCurrentGame()
			}
		},
		methods: {
			messageToggle(type, text) {
				this.msgType = type
				this.messageText = text
				this.$refs.message.open()
			},
			//初始化当前进入游戏的信息（兼容查询进行中和已结束游戏的功能）
			async initGame(){
				const {code,data,message} = await querygamedetailbydm({"code":this.currentGameID})
				if(data.code==="200"){
					//这里采用一次性加载方案 不再需要点击其他功能按钮重复调用接口
					//加载游戏基本信息
					this.setCurrentGameDTO(data.data.game)
					//加载玩家当前座位
					if(this.currentGameDTO.players.length>0){
						let checkSeatNumber = this.currentGameDTO.players.filter(n => {return n.user.id=== this.user.id})[0] || {seatNumber:0}
						this.setUserSeatNum(checkSeatNumber.seatNumber)
					}
					console.log(this.currentGamePlayerSeatNum)
					//加载游戏进程
					this.setGameStatus(data.data.game.processStatus)
					uni.setStorageSync('GAME_STATUS',data.data.game.processStatus)
					//加载当前游戏回合
					this.setGameStageCode(data.data.gameProcessingInfo.curStageCode)
					uni.setStorageSync('GAME_STAGE',data.data.gameProcessingInfo.curStageCode)
					//加载玩家行为 投票记录/结果/投票权限和投票对象情况
					this.setGameStageInfoMap(data.data.gameProcessingInfo.stageInfoMap)
					console.log(Object.keys(this.stageInfoMap))
					console.log(data.data.gameProcessingInfo.stageInfoMap)
					//加载得分情况
					this.setPlayerScoreMap(data.data.gameEndInfo.playerScoreMap)
					this.messageToggle('success', `刷新游戏进度信息成功`)
					
				} else{
					this.messageToggle('error', `刷新玩家准备信息失败:` + data.errMsg)
				}				
			},
			async exitGame() {
				const {code,data,message} = await quitgame({
					"gameCode": this.currentGameID,
					"userId": this.user.id
				})
				if (data.code === "200") {
					this.messageToggle('success', '已成功退出游戏')
					this.clearCurrentGame()
					uni.reLaunch({url: '/pages'})
				} else {
					this.messageToggle('error', `退出游戏失败:` + data.message)
				}
			},
			exit() {
				this.$refs.exitGameDialog.open()
			},
			subExitGame() {
				this.exitGame()
			},
			editGameRole() {
				this.$refs.inputGameRoleDialog.open()
			},
			//录入身份信息
			async subEditGameRole(){
				this.setUserRole(this.currentGameRole)
				console.log(this.gameRoleTrans)
				const {data,code,message} = await submitgamerole({"gameCode":this.currentGameID,"gameRoleCode":this.gameRoleTrans,"userId":this.user.id})
				if(data.code === "200"){
					this.messageToggle('success', '提交身份录入成功，如座位发生变化需重新录入')
				} else{
					this.messageToggle('error', `提交录入身份失败:` + data.message)
				}
			},
			votePlayer(){	
				this.$refs.voteDialog.open()
			},
			//提交投票
			async subVotePlayer(){
				console.log(this.voteCheckbox)
				const {code,data,message} = await addplayeraction({
					"actions":[{
					"actionSeatNumber": this.currentGamePlayerSeatNum,
					"targetSeatNumber": this.voteCheckbox + 1,
					"type": this.gameStageCode === 'police_election'? "police_vote":"exile_vote"
					}],
				"code":this.currentGameID,
				})
				if(data.code==='200'){
					this.messageToggle('success', '本轮投票成功，请等待主持人反馈结果')
				}else{
					this.messageToggle('error', `本轮投票失败:` + data.message)
				}
				this.$refs.voteDialog.close()
			},
			async abandonVote(){
				this.messageToggle('success', '本轮弃票成功,请等待主持人反馈结果')
				//清空允许投票列表
				this.allowVotedPlayer.splice(0)
				this.$refs.voteDialog.close()
			},
			viewVoteRecord(){
				uni.navigateTo({
					url: `/pages/view/common/voterecode-history`
				})
			},
			gameReview(){
				uni.navigateTo({
					url: `/pages/view/common/review-game`
				})
			},
			gameScore(){
				uni.navigateTo({
					url: `/pages/view/common/final-score`
				})
			},
			...mapActions([
				"clearCurrentGame",
			]),
			...mapMutations([
				"setCurrentGameDTO",
				"setGameStatus",
				"setUserSeatNum",
				"setGameStageCode",
				"setUserRole",
				"setGameStageInfoMap",
				"setPlayerScoreMap",
				"setGameResult",
				"setGameStageAction",
				"setGameStageActionList",
				"setGameStageVoteStatus",
			])
		},	
	}
</script>

<style lang="scss" scoped>
	
	.player-control {
		display: flex;
		justify-content: center;
		align-items: center;
		flex: 1;
	}

	.control-btn {
		margin: 20px 10px;
	}
	.vote-info{
		display: flex;
		flex-direction:column;
		justify-content: center;
		align-items: center;
		flex: 1;
		.text{
			display: flex;
			justify-content: flex-start;
			flex-direction:row;
			align-items: center;
			font-size: 14px;
			color: $uni-color-subtitle;
			margin: 5px 10px 5px 5px;
		}
	}
	.uni-data-checkbox{
		padding: 5px;
	}
	
	.managebtn {
		background-color: $uni-color-success;
		font-weight: 700;
	}
</style>
